<template>
  <div>
    <!-- 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告信息 -->
      <el-alert show-icon title="注意:只允许为第三级分类设置相关参数!" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类级联选择框-->
          <el-cascader
              v-model="selectedCateKeys"
              :options="catelist"
              :props="cateProps"
              @change="cateChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签选择-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 添加动态参数面板-->
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addParamsVisible = true">添加参数</el-button>
            <!-- 动态参数表格-->
            <el-table :data="manyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals" :key="index"
                    closable @close="tagHandleClose(index,scope.row)">
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加新标签 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 索引列-->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeManyParamsById(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态属性面板-->
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addParamsVisible = true">添加属性</el-button>
            <!-- 静态参数表格-->
            <el-table :data="onlyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals" :key="index"
                    closable @close="handleClose(tag)">
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加新标签 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="属性名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeManyParamsById(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数-->
    <el-dialog :title="'添加' + paramsTitleTest" :visible.sync="addParamsVisible" width="50%"
      :close-on-click-modal="false" @close="addParamsFormClosed">
      <!-- 修改用户表单区域 -->
      <el-form ref="addParamsFormRef" :model="addParamsForm" :rules="paramsFormRules" label-width="100px">
        <!-- 动态参数名称 -->
        <el-form-item :label="paramsTitleTest + ':'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数-->
    <el-dialog :title="'添加' + paramsTitleTest" :visible.sync="editParamsVisible" width="50%"
      :close-on-click-modal="false">
      <!-- 修改用户表单区域 -->
      <el-form ref="editParamsFormRef" :model="editParamsForm" :rules="paramsFormRules" label-width="100px">
        <!-- 静态属性名称 -->
        <el-form-item :label="paramsTitleTest + ':'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      catelist: [],
      // 级联选择框配置对象
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框选中的数据
      selectedCateKeys: [],
      // 被激活页签的名称
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamsVisible: false,
      editParamsVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      editParamsForm: {},
      paramsFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.catelist = res.data
    },
    cateChange () {
      this.getParamsData()
    },
    // tab页签点击事件
    handleTabClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 根据所选的面板id获取参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }

      // 转换标签数据
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制按钮与文本框显示
        item.inputVisible = false
        // 文本框输入内容
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(res.data)
    },
    addParamsFormClosed () {
      this.$refs.addParamsFormRef.resetFields()
    },
    async addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.$message.success('添加参数成功！')
        this.getParamsData()
        this.addParamsVisible = false
      })
    },
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editParamsForm.attr_vals
          })
        if (res.meta.status !== 200) return this.$message.error('参数信息修改失败！')
        this.$message.success('参数信息修改成功！')
        this.getParamsData()
        this.editParamsVisible = false
      })
    },
    async showEditDialog (id) {
      console.log(id + '-------------')
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        })
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数信息失败')
      }
      this.editParamsForm = res.data
      this.editParamsVisible = true
    },
    removeManyParamsById (id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除参数失败！')
          }
          // this.$message({ type: 'success', message: '删除成功!' })
          this.$message.success('删除参数成功!')
          this.getParamsData()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 文本框失去焦点或按下Enter
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.editTagParams(row)
    },
    showInput (row) {
      row.inputVisible = true
      // 获取焦点 $nextTick-页面元素重新渲染后执行
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    tagHandleClose (index, row) {
      // 删除对应的参数
      row.attr_vals.splice(index, 1)
      this.editTagParams(row)
    },
    // 修改标签
    async editTagParams (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) {
        return this.$message.error('标签信息更新失败！')
      }
      return this.$message.success('标签信息更新成功！')
    }
  },
  computed: {
    // 如果按钮需要被禁用，返回true
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    paramsTitleTest () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 280px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
